package indi.zhifa.engine.starter.minio;

import indi.zhifa.engine.core.minio.properties.MinioConfigProperties;
import indi.zhifa.engine.core.minio.util.impl.MinIoUtilImpl;
import io.minio.MinioClient;
import lombok.RequiredArgsConstructor;
import okhttp3.HttpUrl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

@RequiredArgsConstructor
@AutoConfiguration
@ConditionalOnProperty(prefix = "zhifa.minio",name = "enabled", havingValue = "true")
public class MinioAutoConfig {

    @Bean
    @ConfigurationProperties(prefix = "zhifa.minio")
    public MinioConfigProperties minioConfigProperties(){
        return new MinioConfigProperties();
    }

    @ConditionalOnMissingBean
    @Bean
    public MinioClient minioClient(MinioConfigProperties pMinioConfigProperties) throws NoSuchAlgorithmException, KeyManagementException {

        HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme(pMinioConfigProperties.getSchema()).host(pMinioConfigProperties.getHost());
        if(pMinioConfigProperties.getPort() > 0){
            urlBuilder = urlBuilder.port(pMinioConfigProperties.getPort());
        }

        MinioClient minioClient = MinioClient
                .builder()
                .credentials(pMinioConfigProperties.getAccessKey(), pMinioConfigProperties.getSecretKey())
                .endpoint(urlBuilder.build())
                .build();
        if(pMinioConfigProperties.isIgnoreSsl()){
            minioClient.ignoreCertCheck();
        }
        return minioClient;
    }

    @Bean
    public MinIoUtilImpl minIoUtil(MinioConfigProperties pMinioConfigProperties, MinioClient pMinioClient){
        return new MinIoUtilImpl(pMinioConfigProperties, pMinioClient);
    }

}
